<template>
<div class="cashback-add views-container">
    <el-dialog width="50%" :visible.sync="dialogTableVisible" custom-class="reset-pwd wlm-form-dialog dialog-table">
        <div class="wlm-form" v-if="dialogTableVisible">
            <div class="wlm-form-header wlm-dialog-fixheader">
                <span class="wlm-dialog-inlenr">设置活动</span>
            </div>
            <el-scrollbar wrap-class="scrollbar-wrapper">
                <div class="wlm-form-content">
                    <div class="wlm-dialog-main">
                        <div class="wlm-dialog-content" v-if="formFormatData.formData.goods[$index]">
                            <div class="flex-row flex-align-c" style="margin-bottom:10px;">
                                <span style="margin-right:10px;">当前商品</span>
                                <img style="margin:0 6px;" height="50" width="50" :src="imgPath" alt="">
                                <p>{{goodsName}}</p>
                            </div>
                            <el-table :data="formFormatData.formData.goods[$index]['attr']" style="width: 100%">
                                <el-table-column prop="date" label="商品规格">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.title}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="date" label="价格" min-width="40">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.goods_price}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="date" label="库存" min-width="40">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.stock_num}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="返现金额">
                                    <template slot-scope="scope">
                                        <el-input-number v-model="scope.row.return_money" :controls="false" class="wlm-input-auto" :min="1" :max="((scope.row.goods_price * 100) - 1)/100"></el-input-number>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
            <el-button size="small" type="primary" @click="dialogTableVisible = false">确定</el-button>
        </footer>
    </el-dialog>
    <div class="wlm-form">
        <div class="wlm-form-header">活动设置</div>
        <div class="wlm-form-content">
            <el-form :disabled="$hasFormEnd" ref="info" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="140px" class="retail-form" label-position="right">
                <el-form-item label="活动名称" prop="name">
                    <el-input  v-model.trim="formFormatData.formData.name">
                    </el-input>
                </el-form-item>
                <el-form-item label="活动时间" prop="time">
                    <el-date-picker :disabled="$hasFormEdit" style="width:360px;" :default-time="[`${new Date().getHours()}:${(new Date().getMinutes() + 5).toString().padStart(2,'0')}:00`,'23:59:59']" :picker-options="afterOptions" v-model="formFormatData.formData.time" value-format="timestamp" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="活动渠道" prop="channel">
                    <el-checkbox-group v-model="formFormatData.formData.channel" >
                      <el-checkbox label="2" v-if="JSON.stringify($store.getters.power).indexOf('wxapp')>-1">微信小程序</el-checkbox>
                  <!-- <el-checkbox label="3" v-if="JSON.stringify($store.getters.power).indexOf('H5')>-1">H5</el-checkbox> -->
                  <el-checkbox label="4" v-if="JSON.stringify($store.getters.power).indexOf('wechat')>-1">微信公众号</el-checkbox>

                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div class="wlm-form">
        <div class="wlm-form-header">规则设置</div>
        <div class="wlm-form-content">
            <el-form :disabled="$hasFormEnd" ref="setting" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="140px" class="retail-form" label-position="right">
                <el-form-item label="活动形式">
                    <el-radio-group :disabled="$hasFormEdit" v-model="formFormatData.formData.type">
                        <el-radio :label="10">支付立减</el-radio>
                        <el-radio :label="20">支付返现</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 支付立减不显示所有支付 -->
                <el-form-item label="支付方式" v-if="formFormatData.formData.type==20">
                    <el-radio-group  v-model="formFormatData.formData.pay_type">
                        <el-radio :label="1">所有支付</el-radio>
                        <el-radio :label="2">微信支付</el-radio>
                        <el-radio v-if="formFormatData.formData.channel.includes('4')" :label="3">支付宝支付</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="指定银行卡" v-if="formFormatData.formData.type==10||(formFormatData.formData.type==20&& formFormatData.formData.pay_type==2)">
                    <el-select filterable v-model="formFormatData.formData.bank" placeholder="请选择">
                        <el-option v-for="item in categoryData" :key="`${item.value}`" :label="item.label" :value="`${item.value}`">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="周限制参与活动次数" v-if="formFormatData.formData.type==10&&formFormatData.formData.bank">
                    <el-input v-model="formFormatData.formData.week_limit">
                        <template slot="append">次</template>
                    </el-input>
                    <div class="form-help">填0表示不限制</div>
                </el-form-item>
                <el-form-item label="月限制参与活动次数" v-if="formFormatData.formData.type==10&&formFormatData.formData.bank">
                    <el-input v-model="formFormatData.formData.month_limit">
                        <template slot="append">次</template>
                    </el-input>
                    <div class="form-help">填0表示不限制</div>
                </el-form-item>
                <el-form-item label="支付提示语" v-if="formFormatData.formData.type==10&&formFormatData.formData.bank">
                    <el-input v-model="formFormatData.formData.content">
                    </el-input>
                </el-form-item>
                <el-form-item label="优惠方式" v-if="formFormatData.formData.type==10">
                    <el-radio-group  v-model="formFormatData.formData.discount_type">
                        <el-radio :label="1">定额立减</el-radio>
                        <el-radio :label="2">随机立减</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="立减金额" v-if="formFormatData.formData.type==10&&formFormatData.formData.discount_type==1">
                    <el-input v-model="formFormatData.formData.reduce_money">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="立减区间" v-if="formFormatData.formData.type==10&&formFormatData.formData.discount_type==2">
                    <div class="flex-row">
                        <el-input v-model="formFormatData.formData.min_money"><template slot="append">元</template></el-input><p style="margin:0 12px">至</p>
                        <el-input v-model="formFormatData.formData.max_money"><template slot="append">元</template></el-input>
                    </div>
                </el-form-item>
                <!-- 支付立减不显示返现方式 -->
                <el-form-item label="返现方式" v-if="formFormatData.formData.type==20">
                    <el-radio-group  v-model="formFormatData.formData.return_type">
                        <!-- <el-radio :label="1">微信红包</el-radio> -->
                        <el-radio :label="2">微信零钱</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="参与次数" v-if="formFormatData.formData.type==20" >
                    <el-checkbox :disabled="$hasFormEdit" :true-label="1" :false-label="2" v-model="formFormatData.formData.is_limit">限制每个用户参与本次活动次数</el-checkbox>
                </el-form-item>
                <el-form-item label="次数" v-if="formFormatData.formData.is_limit==1&&formFormatData.formData.type==20" >
                    <el-input :disabled="$hasFormEdit" v-model="formFormatData.formData.limit_num"></el-input>
                </el-form-item>
                <el-form-item label="是否分销">
                    <el-radio-group  v-model="formFormatData.formData.is_dealer">
                        <el-radio :label="1">分销</el-radio>
                        <el-radio :label="2">不分销</el-radio>
                    </el-radio-group>
                    <div class="form-help">分销商品是否还参与分销</div>
                </el-form-item>
                <el-form-item label="活动商品" prop="goods">
                    <choose-goods ref="chooseGoods" :config="chooseGoodsConfig" :changeEvt="filtersChange"></choose-goods>
                    <el-button :disabled="$hasFormEdit" type="primary" @click="goodsToogle">活动商品</el-button>
                    <div class="form-help">选择参加活动的商品</div>
                    <el-table v-if="formFormatData.formData.goods!=''" :data="formFormatData.formData.goods" style="width: 100%">
                        <el-table-column prop="date" label="商品">
                            <template slot-scope="scope">
                                <div class="flex-row">
                                    <img class="logo" v-if="scope.row.image && scope.row.image[0]" :src="scope.row.image[0]['file_path']">
                                    <div class="inner-text">
                                        <p>{{scope.row.goods_name}}</p>
                                        <span>￥:{{scope.row.attr[0]['goods_price']}}</span>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="库存">
                            <template slot-scope="scope">
                                <p>{{scope.row.stock_num || scope.row.stock}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="活动设置" v-if="formFormatData.formData.type!=10">
                            <template slot-scope="scope">
                                <div v-if="scope.row.attr && scope.row.attr[0]['spec_id']!=-1">
                                    <el-button plain @click="showDialog(scope,scope.row.image[0]['file_path'],scope.row.goods_name)">设置返现金额</el-button>
                                </div>
                                <div v-if="scope.row.attr && scope.row.attr[0]['spec_id']==-1" class="flex-row">
                                    <div class="flex-col">
                                        <p class="orders-gray font-12">返现金额</p>
                                        <el-input-number class="wlm-input-auto" style="width:200px;" v-model="scope.row.attr[0]['return_money']" :controls="false" :min="1" :max="Number(scope.row.attr[0]['goods_price'])" placeholder="请输入内容"></el-input-number>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button :disabled="$hasFormEdit" class="wlm-text" type="text" @click="deleteTable(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
        <el-button size="small" @click="formFormatSubmit({ router: { type: 'replace', path: '/application/cashback', code: 1 }})" type="primary" :loading="loading">保存</el-button>
        <router-link tag="span" to="/application/cashback">
            <el-button size="small">返回</el-button>
        </router-link>
    </div>
</div>
</template>

<script>
import ChooseGoods from '@/components/ChooseGoods/index'
import {
  setCashBack,
  getCashBackData,
  getWechatBankList
} from '@/api/application'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'Cashback',
  components: {
    ChooseGoods
  },
  created() {
    getWechatBankList({ type: 1 }).then((response) => {
      const {
        data: {
          data: msgData = []
        }
      } = response
      const result = []
      msgData.map((item, index) => {
        result.push({ value: item[0][0], label: item[0][1] })
      })
      this.categoryData = result
    })
  },
  computed: {
    $hasFormEdit() {
      return this.isFormEdit && this.formFormatData.formData.status !== 1
    },
    $hasFormEnd() {
      return this.isFormEdit && this.formFormatData.formData.status === 3
    }
  },
  data() {
    var checkTime = (rule, value, callback) => {
      const { message } = rule
      const time = this.formFormatData.formData.time
      if ((Array.isArray(time) && time.length === 0) || !Array.isArray(time)) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }

    var checkGoods = (rule, value, callback) => {
      const { message } = rule
      const goods = this.formFormatData.formData.goods
      if (Array.isArray(goods) && goods.length === 0) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }

    return {

      loading: false,
      categoryData: [],
      $index: -1,
      dialogTableVisible: false,
      dialogVisibleImg: false,
      imgPath: '',
      goodsName: '',
      currentRow: [],
      chooseGoodsConfig: {
        type: ['chooseGoods'],
        model: 'normal',
        disabled: [{
          label: 'cashback_id',
          value: 0,
          reverse: true
        }],
        initList: []
      },
      platformConfig: {
        type: ['image'],
        initList: [],
        isMore: false,
        bindKey: {
          key: 'image',
          model: 'img'
        }
      },
      chooseData: [],
      formFormatData: {
        key: ['info', 'setting'],
        model: {
          noCreateEdit: false,
          bindDialog: 'dialogTableVisible'
        },
        api: {
          editForm: {
            api: getCashBackData,
            params: {
              id: ''
            },
            filters: {
              choose: {
                bindInit: ['chooseGoodsConfig']
              }
            }
          },
          submitForm: setCashBack
        },
        formData: {
          name: '',
          limit_num: '',
          pay_type: 1,
          random_string: '',
          return_type: 2,
          bank: '',
          status: '',
          week_limit: '',
          month_limit: '',
          content: '',
          type: 10,
          discount_type: 1,
          reduce_money: '',
          max_money: '',
          min_money: '',
          is_limit: 2,
          time: [],
          is_dealer: 2,
          channel: [],
          goods: []
        },
        rules: {
          name: [{
            message: '请填写活动名称',
            required: true,
            trigger: 'change'
          }],
          channel: [{
            message: '请填写活动渠道',
            required: true,
            trigger: 'change'
          }],
          limit_num: [{
            message: '请填写限制次数',
            required: true,
            trigger: 'change'
          }],
          time: [{
            message: '请选择活动时间',
            required: true,
            validator: checkTime,
            trigger: 'change'
          }],
          goods: [{
            message: '请选择活动商品',
            required: true,
            validator: checkGoods,
            trigger: 'change'
          }]
        }
      }
    }
  },
  methods: {
    filtersChange(val) {
      this.currentRow = val.currentRow
      const displayData = val.displayData
      displayData.map(item => {
        item.attr = JSON.parse(JSON.stringify([...[], ...item.sku]))
        item.attr.map(attritem => {
          if (item.spec_type === 10) {
            attritem.spec_id = -1
          } else if (item.spec_type === 20) {
            attritem.spec_id = attritem.goods_sku_id
          }
          // attritem.return_money = ''
        })
      })
      displayData.map(item => {
        var hasIndex = this.formFormatData.formData.goods.findIndex(tableitem => { return tableitem.goods_id === item.goods_id })
        if (hasIndex === -1) {
          // this.formFormatData.formData.goods.push(item)
          this.formFormatData.formData.goods.push({ goods_id: item.goods_id, goods_name: item.goods_name, image: item.image, spec_type: item.spec_type, attr: item.attr, stock_num: item.stock })
        }
      })
    },
    goodsToogle() {
      const result = []
      this.formFormatData.formData.goods.map(item => {
        result.push(item.goods_id)
      })
      this.$refs.chooseGoods.currentRow = result
      this.$refs.chooseGoods.toggle()
    },
    deleteTable(scope) {
      this.formFormatData.formData.goods.splice(scope.$index, 1)
      this.currentRow.splice(scope.$index, 1)
    },
    showDialog(scope, img, name) {
      if (scope) {
        this.$index = scope.$index
        this.imgPath = img
        this.goodsName = name
        this.dialogTableVisible = true
      }
    }
  }
}
</script>

//

<style lang="scss" scoped>
.cashback-add {
    .logo {
        height: 40px;
        width: 40px;
        border-radius: 50%;
        vertical-align: middle;
        margin-right: 6px;
    }
}
</style>
